//! MySQL 数据库填充实现

#[cfg(feature = "database")]
use sqlx::{MySql, Pool, Row};
use std::collections::HashMap;
use librarys::random_letters;
use serde_json::Value;
use crate::error::{DataForgeError, Result};
use crate::generators::{number, datetime, internet};
use crate::db::schema::{TableSchema, FieldSchema, DataType, FieldGeneratorType};
use super::{DatabaseFiller, FillingConfig, FillingStats, ConnectionConfig};

/// MySQL 专用数据填充器
#[cfg(feature = "database")]
pub struct MySqlFiller {
    pool: Pool<MySql>,
    config: FillingConfig,
    stats: FillingStats,
}

#[cfg(feature = "database")]
impl MySqlFiller {
    /// 创建新的 MySQL 填充器
    pub async fn new(connection_string: &str, config: FillingConfig) -> Result<Self> {
        let pool = sqlx::mysql::MySqlPoolOptions::new()
            .max_connections(10)
            .connect(connection_string)
            .await
            .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;

        Ok(Self {
            pool,
            config,
            stats: FillingStats::default(),
        })
    }

    /// 从连接配置创建
    pub async fn from_config(config: ConnectionConfig, filling_config: FillingConfig) -> Result<Self> {
        let connection_string = config.to_connection_string()?;
        Self::new(&connection_string, filling_config).await
    }

    /// 检查表是否存在
    pub async fn table_exists(&self, table_name: &str) -> Result<bool> {
        let query = "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?";
        let row = sqlx::query(query)
            .bind(table_name)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| DataForgeError::database(&format!("Failed to check table existence: {}", e)))?;
        
        let count: i64 = row.try_get("count")
            .map_err(|e| DataForgeError::database(&format!("Failed to get count: {}", e)))?;
        
        Ok(count > 0)
    }

    /// 获取表结构
    pub async fn get_table_schema(&self, table_name: &str) -> Result<TableSchema> {
        let query = r#"
            SELECT 
                COLUMN_NAME as column_name,
                DATA_TYPE as data_type,
                IS_NULLABLE as is_nullable,
                COLUMN_DEFAULT as column_default,
                CHARACTER_MAXIMUM_LENGTH as max_length,
                NUMERIC_PRECISION as numeric_precision,
                NUMERIC_SCALE as numeric_scale
            FROM information_schema.COLUMNS 
            WHERE table_schema = DATABASE() AND table_name = ?
            ORDER BY ORDINAL_POSITION
        "#;

        let rows = sqlx::query(query)
            .bind(table_name)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| DataForgeError::database(&format!("Failed to get table schema: {}", e)))?;

        let mut fields = Vec::new();
        for row in rows {
            let column_name: String = row.try_get("column_name")?;
            let data_type_str: String = row.try_get("data_type")?;
            let is_nullable: String = row.try_get("is_nullable")?;
            let max_length: Option<u32> = row.try_get("max_length").ok();

            let data_type = self.mysql_type_to_datatype(&data_type_str, max_length);
            let nullable = is_nullable.to_uppercase() == "YES";

            fields.push(FieldSchema {
                name: column_name,
                data_type,
                constraints: crate::db::schema::FieldConstraints {
                    nullable,
                    unique: false,
                    default: None,
                    pattern: None,
                    min: None,
                    max: None,
                },
                description: None,
                generator_config: None,
                generator_type: None,
            });
        }

        Ok(TableSchema {
            name: table_name.to_string(),
            fields,
            primary_key: None,
            indexes: vec![],
            description: None,
        })
    }

    /// 填充指定表的随机数据
    pub async fn fill_table(&mut self, table_name: &str, count: usize) -> Result<usize> {
        // 检查表是否存在
        if !self.table_exists(table_name).await? {
            return Err(DataForgeError::database(&format!("Table '{}' does not exist", table_name)));
        }

        // 获取表结构
        let schema = self.get_table_schema(table_name).await?;
        
        // 生成数据
        let data = self.generate_table_data(count, &schema)?;
        
        // 插入数据
        self.batch_insert(table_name, data).await
    }

    /// 根据表结构生成数据
    fn generate_table_data(&self, count: usize, schema: &TableSchema) -> Result<Vec<HashMap<String, Value>>> {
        let mut data = Vec::with_capacity(count);

        // 通用数据生成逻辑，根据 schema 生成
        for _i in 1..=count {
            let mut row = HashMap::new();
            
            for field in &schema.fields {
                let value = self.generate_value_for_field(field)?;
                row.insert(field.name.clone(), value);
            }
            
            data.push(row);
        }
        
        Ok(data)
    }
    
    /// MySQL 类型转换为内部数据类型
    fn mysql_type_to_datatype(&self, mysql_type: &str, max_length: Option<u32>) -> DataType {
        match mysql_type.to_lowercase().as_str() {
            "varchar" | "char" | "text" | "tinytext" | "mediumtext" | "longtext" => {
                DataType::String { max_length: max_length.map(|l| l as usize) }
            },
            "int" | "tinyint" | "smallint" | "mediumint" | "bigint" => {
                DataType::Integer { min: None, max: None }
            },
            "float" | "double" | "decimal" => {
                DataType::Float { min: None, max: None, precision: None }
            },
            "boolean" | "bool" => DataType::Boolean,
            "date" => DataType::Date { format: None },
            "datetime" | "timestamp" => DataType::DateTime { format: None },
            "time" => DataType::Time { format: None },
            "json" => DataType::Json,
            _ => DataType::String { max_length: Some(255) },
        }
    }
    
    /// 生成创建表的SQL语句
    #[allow(dead_code)]
    fn generate_create_table_sql(&self, schema: &TableSchema) -> Result<String> {
        use crate::db::schema::DataType;
        
        let mut sql = format!("CREATE TABLE IF NOT EXISTS {} (", schema.name);
        
        let field_definitions: Vec<String> = schema.fields.iter().map(|field| {
            let data_type = match &field.data_type {
                DataType::String { max_length } => {
                    format!("VARCHAR({})", max_length.unwrap_or(255))
                },
                DataType::Integer { .. } => "INT".to_string(),
                DataType::Float { .. } => "FLOAT".to_string(),
                DataType::Boolean => "BOOLEAN".to_string(),
                DataType::DateTime { .. } => "DATETIME".to_string(),
                DataType::Date { .. } => "DATE".to_string(),
                DataType::Email => "VARCHAR(255)".to_string(),
                DataType::Phone { .. } => "VARCHAR(20)".to_string(),
                _ => "TEXT".to_string(),
            };
            
            let mut def = format!("{} {}", field.name, data_type);
            
            if !field.constraints.nullable {
                def.push_str(" NOT NULL");
            }
            
            if field.constraints.unique {
                def.push_str(" UNIQUE");
            }
            
            def
        }).collect();
        
        sql.push_str(&field_definitions.join(", "));
        
        if let Some(ref pk) = schema.primary_key {
            sql.push_str(&format!(", PRIMARY KEY ({})", pk.join(", ")));
        }
        
        sql.push_str(")");
        Ok(sql)
    }

    /// 根据字段类型生成值
    fn generate_value_for_field(&self, field: &FieldSchema) -> Result<Value> {
        // 首先检查是否有指定的生成器类型
        if let Some(generator_type) = &field.generator_type {
            return self.generate_value_by_generator_type(field, generator_type);
        }
        
        // 如果没有指定生成器类型，则根据数据类型自动生成
        match &field.data_type {
            DataType::String { max_length } => {
                let max_len = max_length.unwrap_or(255) as usize;
                let len = std::cmp::min(10, max_len);
                Ok(Value::String(random_letters(len)))
            },
            DataType::Integer { min, max } => {
                let min_val = min.unwrap_or(0);
                let max_val = max.unwrap_or(1000000);
                Ok(Value::Number(serde_json::Number::from(number::random_int(min_val as i32, max_val as i32))))
            },
            DataType::Float { .. } => {
                Ok(Value::Number(serde_json::Number::from_f64(number::random_float(0.0, 100.0)).unwrap()))
            },
            DataType::Boolean => {
                Ok(Value::Bool(rand::random()))
            },
            DataType::DateTime { .. } => {
                Ok(Value::String(datetime::iso8601()))
            },
            DataType::Date { .. } => {
                Ok(Value::String(datetime::date_iso()))
            },
            DataType::Email => {
                Ok(Value::String(internet::email()))
            },
            DataType::Phone { .. } => {
                Ok(Value::String(number::phone_number_cn()))
            },
            _ => {
                Ok(Value::String("default_value".to_string()))
            }
        }
    }
    
    /// 根据指定的生成器类型生成值
    fn generate_value_by_generator_type(&self, field: &FieldSchema, generator_type: &FieldGeneratorType) -> Result<Value> {
        match generator_type {
            FieldGeneratorType::Default => {
                // 使用默认生成逻辑
                self.generate_value_for_field(field)
            },
            FieldGeneratorType::Custom(generator_name) => {
                // 使用自定义生成器（这里简化处理，实际项目中可能需要更复杂的逻辑）
                Ok(Value::String(format!("custom_{}", generator_name)))
            },
            FieldGeneratorType::RandomString => {
                let len = match &field.data_type {
                    DataType::String { max_length } => max_length.unwrap_or(10),
                    _ => 10,
                };
                Ok(Value::String(random_letters(len as usize)))
            },
            FieldGeneratorType::RandomInteger => {
                Ok(Value::Number(serde_json::Number::from(crate::generators::random_int(0, 1000000))))
            },
            FieldGeneratorType::RandomFloat => {
                Ok(Value::Number(serde_json::Number::from_f64(crate::generators::random_float(0.0, 1000.0)).unwrap()))
            },
            FieldGeneratorType::RandomBoolean => {
                Ok(Value::Bool(crate::generators::random_bool()))
            },
            FieldGeneratorType::CurrentTimestamp => {
                Ok(Value::String(datetime::iso8601()))
            },
            FieldGeneratorType::RandomDate => {
                Ok(Value::String(datetime::date_iso()))
            },
            FieldGeneratorType::RandomDateTime => {
                Ok(Value::String(datetime::iso8601()))
            },
            FieldGeneratorType::RandomEmail => {
                Ok(Value::String(crate::generators::internet::email()))
            },
            FieldGeneratorType::RandomPhone => {
                Ok(Value::String(crate::generators::number::phone_number_cn()))
            },
            FieldGeneratorType::RandomUrl => {
                Ok(Value::String(crate::generators::internet::url()))
            },
            FieldGeneratorType::Uuid => {
                Ok(Value::String(crate::generators::uuid_v4()))
            },
            FieldGeneratorType::Name => {
                // 根据语言设置生成相应语言的姓名
                match crate::generation::DataForge::default().language() {
                    crate::generation::Language::ZhCN => {
                        Ok(Value::String(crate::generators::name::zh_cn_fullname()))
                    },
                    crate::generation::Language::EnUS => {
                        Ok(Value::String(crate::generators::name::en_us_fullname()))
                    },
                    crate::generation::Language::JaJP => {
                        Ok(Value::String(crate::generators::name::ja_jp_fullname()))
                    },
                }
            },
            FieldGeneratorType::CompanyName => {
                Ok(Value::String(format!("Company {}", crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::Address => {
                // 根据语言设置生成相应语言的地址
                match crate::generation::DataForge::default().language() {
                    crate::generation::Language::ZhCN => {
                        Ok(Value::String(format!("{}市{}区{}街道{}", 
                            crate::generators::address::zh_city(), 
                            crate::generators::address::zh_city(), 
                            crate::generators::random_int(1, 100),
                            crate::generators::random_int(1, 1000))))
                    },
                    crate::generation::Language::EnUS => {
                        Ok(Value::String(format!("{} Street {}, {}, {}", 
                            crate::generators::address::us_city(),
                            crate::generators::random_int(1, 1000),
                            crate::generators::address::us_city(),
                            crate::generators::address::us_state())))
                    },
                    crate::generation::Language::JaJP => {
                        Ok(Value::String(format!("{}{}{}丁目{}", 
                            crate::generators::address::us_city(),  // 使用us_city作为替代
                            crate::generators::address::us_city(),  // 使用us_city作为替代
                            crate::generators::random_int(1, 20),
                            crate::generators::random_int(1, 20))))
                    },
                }
            },
            FieldGeneratorType::ProductName => {
                let products = ["Laptop", "Smartphone", "Tablet", "Watch", "Headphones", "Speaker"];
                let product = products[crate::generators::random_int(0, products.len() as i32 - 1) as usize];
                Ok(Value::String(format!("{} {}", product, crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::OrderStatus => {
                let statuses = ["Pending", "Processing", "Shipped", "Delivered", "Cancelled"];
                let status = statuses[crate::generators::random_int(0, statuses.len() as i32 - 1) as usize];
                Ok(Value::String(status.to_string()))
            },
        }
    }

    /// 批量插入数据（异步版本）
    pub async fn batch_insert(&mut self, table_name: &str, data: Vec<HashMap<String, Value>>) -> Result<usize> {
        if data.is_empty() {
            return Ok(0);
        }

        let start_time = std::time::Instant::now();
        let mut total_inserted = 0;

        // 分批插入
        for chunk in data.chunks(self.config.batch_size) {
            let inserted = self.insert_chunk(table_name, chunk).await?;
            total_inserted += inserted;
        }

        // 更新统计信息
        self.stats.successful_rows += total_inserted;
        self.stats.processing_time_ms += start_time.elapsed().as_millis() as u64;
        self.stats.calculate_speed();

        Ok(total_inserted)
    }

    /// 插入单个数据块
    async fn insert_chunk(&self, table_name: &str, chunk: &[HashMap<String, Value>]) -> Result<usize> {
        if chunk.is_empty() {
            return Ok(0);
        }

        // 获取所有字段名
        let fields: Vec<String> = chunk[0].keys().cloned().collect();
        let field_list = fields.join(", ");
        let placeholders = fields.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
        
        let sql = format!("INSERT INTO {} ({}) VALUES ({})", table_name, field_list, placeholders);

        let mut transaction = self.pool.begin().await
            .map_err(|e| DataForgeError::database(&format!("Failed to start transaction: {}", e)))?;

        for row in chunk {
            let mut query = sqlx::query(&sql);
            
            for field in &fields {
                let value = row.get(field).unwrap_or(&Value::Null);
                query = match value {
                    Value::String(s) => query.bind(s),
                    Value::Number(n) => {
                        if let Some(i) = n.as_i64() {
                            query.bind(i)
                        } else if let Some(f) = n.as_f64() {
                            query.bind(f)
                        } else {
                            query.bind(n.to_string())
                        }
                    },
                    Value::Bool(b) => query.bind(*b),
                    Value::Null => query.bind(Option::<String>::None),
                    _ => query.bind(value.to_string()),
                };
            }
            
            query.execute(&mut *transaction).await
                .map_err(|e| DataForgeError::database(&format!("Failed to execute insert: {}", e)))?;
        }

        transaction.commit().await
            .map_err(|e| DataForgeError::database(&format!("Failed to commit transaction: {}", e)))?;

        Ok(chunk.len())
    }
}

/// MySQL 填充器的同步包装器
pub struct MySqlFillerSync {
    pub connection_string: String,
    pub config: FillingConfig,
    pub stats: FillingStats,
}

impl MySqlFillerSync {
    /// 创建同步版本的 MySQL 填充器
    pub fn new(connection_string: String, config: FillingConfig) -> Self {
        Self {
            connection_string,
            config,
            stats: FillingStats::default(),
        }
    }

    /// 从连接配置创建
    pub fn from_config(config: ConnectionConfig, filling_config: FillingConfig) -> Result<Self> {
        let connection_string = config.to_connection_string()?;
        Ok(Self::new(connection_string, filling_config))
    }
    
    /// 生成创建表的SQL语句
    fn generate_create_table_sql(&self, schema: &TableSchema) -> Result<String> {
        use crate::db::schema::DataType;
        
        let mut sql = format!("CREATE TABLE IF NOT EXISTS {} (", schema.name);
        
        let field_definitions: Vec<String> = schema.fields.iter().map(|field| {
            let data_type = match &field.data_type {
                DataType::String { max_length } => {
                    format!("VARCHAR({})", max_length.unwrap_or(255))
                },
                DataType::Integer { .. } => "INT".to_string(),
                DataType::Float { .. } => "FLOAT".to_string(),
                DataType::Boolean => "BOOLEAN".to_string(),
                DataType::DateTime { .. } => "DATETIME".to_string(),
                DataType::Date { .. } => "DATE".to_string(),
                DataType::Email => "VARCHAR(255)".to_string(),
                DataType::Phone { .. } => "VARCHAR(20)".to_string(),
                _ => "TEXT".to_string(),
            };
            
            let mut def = format!("{} {}", field.name, data_type);
            
            if !field.constraints.nullable {
                def.push_str(" NOT NULL");
            }
            
            if field.constraints.unique {
                def.push_str(" UNIQUE");
            }
            
            def
        }).collect();
        
        sql.push_str(&field_definitions.join(", "));
        
        if let Some(ref pk) = schema.primary_key {
            sql.push_str(&format!(", PRIMARY KEY ({})", pk.join(", ")));
        }
        
        sql.push_str(")");
        Ok(sql)
    }

    /// 检查表是否存在
    pub fn table_exists(&self, table_name: &str) -> Result<bool> {
        // 使用同步的运行时来执行异步操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            let query = "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?";
            let row = sqlx::query(query)
                .bind(table_name)
                .fetch_one(&pool)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to check table existence: {}", e)))?;
            
            let count: i64 = row.try_get("count")
                .map_err(|e| DataForgeError::database(&format!("Failed to get count: {}", e)))?;
            
            pool.close().await;
            Ok(count > 0)
        })
    }

    /// 获取表结构
    pub fn get_table_schema(&self, table_name: &str) -> Result<TableSchema> {
        // 使用同步的运行时来执行异步操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            let query = r#"
                SELECT 
                    COLUMN_NAME as column_name,
                    DATA_TYPE as data_type,
                    IS_NULLABLE as is_nullable,
                    COLUMN_DEFAULT as column_default,
                    CHARACTER_MAXIMUM_LENGTH as max_length,
                    NUMERIC_PRECISION as numeric_precision,
                    NUMERIC_SCALE as numeric_scale
                FROM information_schema.COLUMNS 
                WHERE table_schema = DATABASE() AND table_name = ?
                ORDER BY ORDINAL_POSITION
            "#;

            let rows = sqlx::query(query)
                .bind(table_name)
                .fetch_all(&pool)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to get table schema: {}", e)))?;

            let mut fields = Vec::new();
            for row in rows {
                let column_name: String = row.try_get("column_name")
                    .map_err(|e| DataForgeError::database(&format!("Failed to get column_name: {}", e)))?;
                let data_type_str: String = row.try_get("data_type")
                    .map_err(|e| DataForgeError::database(&format!("Failed to get data_type: {}", e)))?;
                let is_nullable: String = row.try_get("is_nullable")
                    .map_err(|e| DataForgeError::database(&format!("Failed to get is_nullable: {}", e)))?;
                let max_length: Option<u32> = row.try_get("max_length").ok();

                let data_type = self.mysql_type_to_datatype(&data_type_str, max_length);
                let nullable = is_nullable.to_uppercase() == "YES";

                fields.push(FieldSchema {
                    name: column_name,
                    data_type,
                    constraints: crate::db::schema::FieldConstraints {
                        nullable,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                });
            }
            
            pool.close().await;
            
            Ok(TableSchema {
                name: table_name.to_string(),
                fields,
                primary_key: None,
                indexes: vec![],
                description: None,
            })
        })
    }

    /// MySQL 类型转换为内部数据类型
    fn mysql_type_to_datatype(&self, mysql_type: &str, max_length: Option<u32>) -> DataType {
        match mysql_type.to_lowercase().as_str() {
            "varchar" | "char" | "text" | "tinytext" | "mediumtext" | "longtext" => {
                DataType::String { max_length: max_length.map(|l| l as usize) }
            },
            "int" | "tinyint" | "smallint" | "mediumint" | "bigint" => {
                DataType::Integer { min: None, max: None }
            },
            "float" | "double" | "decimal" => {
                DataType::Float { min: None, max: None, precision: None }
            },
            "boolean" | "bool" => DataType::Boolean,
            "date" => DataType::Date { format: None },
            "datetime" | "timestamp" => DataType::DateTime { format: None },
            "time" => DataType::Time { format: None },
            "json" => DataType::Json,
            _ => DataType::String { max_length: Some(255) },
        }
    }

    /// 通用表填充方法
    pub fn fill_table(&mut self, table_name: &str, count: usize) -> Result<usize> {
        let start_time = std::time::Instant::now();
        
        // 检查表是否存在
        if !self.table_exists(table_name)? {
            return Err(DataForgeError::database(&format!("Table '{}' does not exist", table_name)));
        }

        // 获取表结构
        let schema = self.get_table_schema(table_name)?;
        
        // 生成数据
        let data = self.generate_table_data(count, &schema)?;
        
        // 执行真正的批量插入
        let inserted = self.batch_insert(table_name, data)?;
        
        // 更新统计信息
        self.stats.total_rows = count;
        self.stats.successful_rows = inserted;
        self.stats.processing_time_ms = start_time.elapsed().as_millis() as u64;
        self.stats.calculate_speed();

        #[cfg(debug_assertions)]
        {
            println!("成功插入 {} 条记录到表 {}", inserted, table_name);
            println!("处理时间: {}ms", self.stats.processing_time_ms);
        }

        Ok(inserted)
    }

    /// 根据表结构生成数据
    fn generate_table_data(&self, count: usize, schema: &TableSchema) -> Result<Vec<HashMap<String, Value>>> {
        let mut data = Vec::with_capacity(count);

        // 通用数据生成逻辑，根据 schema 生成
        for _i in 1..=count {
            let mut row = HashMap::new();
            
            for field in &schema.fields {
                let value = self.generate_value_for_field(field)?;
                row.insert(field.name.clone(), value);
            }
            
            data.push(row);
        }
        
        Ok(data)
    }

    /// 根据字段类型生成值
    fn generate_value_for_field(&self, field: &FieldSchema) -> Result<Value> {
        // 首先检查是否有指定的生成器类型
        if let Some(generator_type) = &field.generator_type {
            return self.generate_value_by_generator_type(field, generator_type);
        }
        
        // 如果没有指定生成器类型，则根据数据类型自动生成
        match &field.data_type {
            DataType::String { max_length } => {
                let max_len = max_length.unwrap_or(255) as usize;
                let len = std::cmp::min(10, max_len);
                Ok(Value::String(random_letters(len)))
            },
            DataType::Integer { min, max } => {
                let min_val = min.unwrap_or(0);
                let max_val = max.unwrap_or(1000000);
                Ok(Value::Number(serde_json::Number::from(number::random_int(min_val as i32, max_val as i32))))
            },
            DataType::Float { .. } => {
                Ok(Value::Number(serde_json::Number::from_f64(number::random_float(0.0, 100.0)).unwrap()))
            },
            DataType::Boolean => {
                Ok(Value::Bool(rand::random()))
            },
            DataType::DateTime { .. } => {
                Ok(Value::String(datetime::iso8601()))
            },
            DataType::Date { .. } => {
                Ok(Value::String(datetime::date_iso()))
            },
            DataType::Email => {
                Ok(Value::String(internet::email()))
            },
            DataType::Phone { .. } => {
                Ok(Value::String(number::phone_number_cn()))
            },
            _ => {
                Ok(Value::String("default_value".to_string()))
            }
        }
    }
    
    /// 根据指定的生成器类型生成值
    fn generate_value_by_generator_type(&self, field: &FieldSchema, generator_type: &FieldGeneratorType) -> Result<Value> {
        match generator_type {
            FieldGeneratorType::Default => {
                // 使用默认生成逻辑
                self.generate_value_for_field(field)
            },
            FieldGeneratorType::Custom(generator_name) => {
                // 使用自定义生成器（这里简化处理，实际项目中可能需要更复杂的逻辑）
                Ok(Value::String(format!("custom_{}", generator_name)))
            },
            FieldGeneratorType::RandomString => {
                let len = match &field.data_type {
                    DataType::String { max_length } => max_length.unwrap_or(10),
                    _ => 10,
                };
                Ok(Value::String(random_letters(len as usize)))
            },
            FieldGeneratorType::RandomInteger => {
                Ok(Value::Number(serde_json::Number::from(crate::generators::random_int(0, 1000000))))
            },
            FieldGeneratorType::RandomFloat => {
                Ok(Value::Number(serde_json::Number::from_f64(crate::generators::random_float(0.0, 1000.0)).unwrap()))
            },
            FieldGeneratorType::RandomBoolean => {
                Ok(Value::Bool(crate::generators::random_bool()))
            },
            FieldGeneratorType::CurrentTimestamp => {
                Ok(Value::String(datetime::iso8601()))
            },
            FieldGeneratorType::RandomDate => {
                Ok(Value::String(datetime::date_iso()))
            },
            FieldGeneratorType::RandomDateTime => {
                Ok(Value::String(datetime::iso8601()))
            },
            FieldGeneratorType::RandomEmail => {
                Ok(Value::String(crate::generators::internet::email()))
            },
            FieldGeneratorType::RandomPhone => {
                Ok(Value::String(crate::generators::number::phone_number_cn()))
            },
            FieldGeneratorType::RandomUrl => {
                Ok(Value::String(crate::generators::internet::url()))
            },
            FieldGeneratorType::Uuid => {
                Ok(Value::String(crate::generators::uuid_v4()))
            },
            FieldGeneratorType::Name => {
                Ok(Value::String(crate::generators::name::zh_cn_fullname()))
            },
            FieldGeneratorType::CompanyName => {
                Ok(Value::String(format!("Company {}", crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::Address => {
                Ok(Value::String(format!("{} Street {}", 
                    crate::generators::address::zh_city(), 
                    crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::ProductName => {
                let products = ["Laptop", "Smartphone", "Tablet", "Watch", "Headphones", "Speaker"];
                let product = products[crate::generators::random_int(0, products.len() as i32 - 1) as usize];
                Ok(Value::String(format!("{} {}", product, crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::OrderStatus => {
                let statuses = ["Pending", "Processing", "Shipped", "Delivered", "Cancelled"];
                let status = statuses[crate::generators::random_int(0, statuses.len() as i32 - 1) as usize];
                Ok(Value::String(status.to_string()))
            },
        }
    }

    /// 批量插入数据（同步版本）
    pub fn batch_insert(&mut self, table_name: &str, data: Vec<HashMap<String, Value>>) -> Result<usize> {
        if data.is_empty() {
            return Ok(0);
        }

        let start_time = std::time::Instant::now();
        let mut total_inserted = 0;

        // 分批插入
        for chunk in data.chunks(self.config.batch_size) {
            let inserted = self.insert_chunk(table_name, chunk)?;
            total_inserted += inserted;
        }

        // 更新统计信息
        self.stats.successful_rows += total_inserted;
        self.stats.processing_time_ms += start_time.elapsed().as_millis() as u64;
        self.stats.calculate_speed();

        Ok(total_inserted)
    }

    /// 插入单个数据块
    fn insert_chunk(&self, table_name: &str, chunk: &[HashMap<String, Value>]) -> Result<usize> {
        if chunk.is_empty() {
            return Ok(0);
        }

        // 使用同步的运行时来执行异步操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            // 获取所有字段名
            let fields: Vec<String> = chunk[0].keys().cloned().collect();
            let field_list = fields.join(", ");
            let placeholders = fields.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
            
            let sql = format!("INSERT INTO {} ({}) VALUES ({})", table_name, field_list, placeholders);

            let mut transaction = pool.begin().await
                .map_err(|e| DataForgeError::database(&format!("Failed to start transaction: {}", e)))?;

            for row in chunk {
                let mut query = sqlx::query(&sql);
                
                for field in &fields {
                    let value = row.get(field).unwrap_or(&Value::Null);
                    query = match value {
                        Value::String(s) => query.bind(s),
                        Value::Number(n) => {
                            if let Some(i) = n.as_i64() {
                                query.bind(i)
                            } else if let Some(f) = n.as_f64() {
                                query.bind(f)
                            } else {
                                query.bind(n.to_string())
                            }
                        },
                        Value::Bool(b) => query.bind(*b),
                        Value::Null => query.bind(Option::<String>::None),
                        _ => query.bind(value.to_string()),
                    };
                }
                
                query.execute(&mut *transaction).await
                    .map_err(|e| DataForgeError::database(&format!("Failed to execute insert: {}", e)))?;
            }

            transaction.commit().await
                .map_err(|e| DataForgeError::database(&format!("Failed to commit transaction: {}", e)))?;
            
            pool.close().await;
            Ok(chunk.len())
        })
    }

}

impl DatabaseFiller for MySqlFillerSync {
    fn create_table(&mut self, schema: &TableSchema) -> Result<()> {
        // 使用真正的 SQL 执行创建表操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            // 生成 CREATE TABLE SQL 语句
            let sql = self.generate_create_table_sql(schema)?;
            
            sqlx::query(&sql)
                .execute(&pool)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to create table: {}", e)))?;
            
            pool.close().await;
            Ok(())
        })
    }

    fn insert_data(&mut self, table_name: &str, data: Vec<HashMap<String, Value>>) -> Result<()> {
        // 使用真正的数据库插入
        self.batch_insert(table_name, data)?;
        Ok(())
    }

    fn batch_insert(&mut self, table_name: &str, data: Vec<HashMap<String, Value>>) -> Result<()> {
        // 使用真正的批量插入（调用实例方法）
        let _inserted = MySqlFillerSync::batch_insert(self, table_name, data)?;
        Ok(())
    }

    fn get_stats(&self) -> FillingStats {
        self.stats.clone()
    }

    fn truncate_table(&mut self, table_name: &str) -> Result<()> {
        // 使用真正的 SQL 执行截断表操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            let sql = format!("TRUNCATE TABLE {}", table_name);
            sqlx::query(&sql)
                .execute(&pool)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to truncate table: {}", e)))?;
            
            pool.close().await;
            Ok(())
        })
    }

    fn drop_table(&mut self, table_name: &str) -> Result<()> {
        // 使用真正的 SQL 执行删除表操作
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| DataForgeError::database(&format!("Failed to create runtime: {}", e)))?;
        
        rt.block_on(async {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(1)
                .connect(&self.connection_string)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to connect to MySQL: {}", e)))?;
            
            let sql = format!("DROP TABLE IF EXISTS {}", table_name);
            sqlx::query(&sql)
                .execute(&pool)
                .await
                .map_err(|e| DataForgeError::database(&format!("Failed to drop table: {}", e)))?;
            
            pool.close().await;
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::filling::ConnectionConfig;
    use crate::{forge, name};

    #[test]
    fn test_mysql_filler_sync_creation() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        
        let filler = MySqlFillerSync::from_config(config, filling_config);
        assert!(filler.is_ok());
    }

    #[test]
    fn test_mysql_connection_string() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        
        let connection_string = config.to_connection_string().unwrap();
        assert!(connection_string.contains("mysql://root:Aa123456@localhost:13307/demo"));
    }

    #[test]
    fn test_generate_sample_employee() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        let filler = MySqlFillerSync::from_config(config, filling_config).unwrap();
        
        let employee = generate_sample_employee(1);
        assert!(employee.is_object());
        // 更新测试以适应动态生成方式
        // 我们现在验证生成的对象至少有一个字段，而不是特定的硬编码字段
        assert!(!employee.as_object().unwrap().is_empty());
    }

    #[test]
    fn test_generate_sample_employee_with_actual_schema() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        let filler = MySqlFillerSync::from_config(config, filling_config).unwrap();
        
        // 测试获取表结构的功能
        let _schema_result = filler.get_table_schema("employees");
        // 注意：在没有真实数据库连接的测试环境中，这个调用可能会失败
        // 但我们仍然可以测试错误处理路径
        
        // 无论如何，generate_sample_employee 应该能够生成数据
        let employee = generate_sample_employee(1);
        assert!(employee.is_object());
        // 现在我们只验证至少有一个字段存在，而不是特定的硬编码字段
        assert!(!employee.as_object().unwrap().is_empty());
    }

    #[test]
    fn test_dynamic_schema_generation() {
        // 创建一个自定义的表结构来测试动态生成
        let custom_schema = TableSchema {
            name: "custom_employees".to_string(),
            fields: vec![
                FieldSchema {
                    name: "employee_id".to_string(),
                    data_type: DataType::Integer { min: None, max: None },
                    constraints: crate::db::schema::FieldConstraints {
                        nullable: false,
                        unique: true,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "full_name".to_string(),
                    data_type: DataType::String { max_length: Some(100) },
                    constraints: crate::db::schema::FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "birth_date".to_string(),
                    data_type: DataType::Date { format: None },
                    constraints: crate::db::schema::FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "salary".to_string(),
                    data_type: DataType::Integer { min: Some(0), max: Some(1000000) },
                    constraints: crate::db::schema::FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["employee_id".to_string()]),
            indexes: vec![],
            description: None,
        };
        
        // 使用自定义表结构生成数据
        let employee_data = crate::filling::utils::generate_sample_data_by_schema(&custom_schema, 1);
        
        // 验证生成的数据字段与表结构匹配
        assert!(employee_data.is_object());
        let employee_obj = employee_data.as_object().unwrap();
        
        // 验证所有定义的字段都存在
        assert!(employee_obj.contains_key("employee_id"));
        assert!(employee_obj.contains_key("full_name"));
        assert!(employee_obj.contains_key("birth_date"));
        assert!(employee_obj.contains_key("salary"));
        
        // 验证字段值类型正确
        assert!(employee_obj.get("employee_id").unwrap().is_number());
        assert!(employee_obj.get("full_name").unwrap().is_string());
        assert!(employee_obj.get("birth_date").unwrap().is_string());
        assert!(employee_obj.get("salary").unwrap().is_number());
    }

    #[test]
    fn test_fill_employees_table() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        let mut filler = MySqlFillerSync::from_config(config, filling_config).unwrap();
        
        let result = filler.fill_table("employees", 10);
        match &result {
            Ok(count) => {
                println!("成功插入 {} 条记录", count);
            },
            Err(e) => {
                println!("填充数据失败: {}", e);
                // 这个测试可能因为没有真实的MySQL服务器而失败
                // 在没有数据库连接的情况下，这是预期的行为
                return;
            }
        }
        
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 10);
        
        let stats = filler.get_stats();
        assert_eq!(stats.successful_rows, 10);
    }

    #[test]
    fn test_table_schema() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        let filler = MySqlFillerSync::from_config(config, filling_config).unwrap();
        
        let schema = filler.get_table_schema("employees");
        match &schema {
            Ok(s) => {
                println!("成功获取表结构: {}", s.name);
                println!("字段数: {}", s.fields.len());
            },
            Err(e) => {
                println!("获取表结构失败: {}", e);
                // 这个测试可能因为没有真实的MySQL服务器而失败
                // 在没有数据库连接的情况下，这是预期的行为
                return;
            }
        }
        
        assert!(schema.is_ok());
        
        let schema = schema.unwrap();
        assert_eq!(schema.name, "employees");
        assert!(!schema.fields.is_empty());
    }

    #[test]
    fn test_batch_insert() {
        let config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307);
        let filling_config = FillingConfig::default();
        let mut filler = MySqlFillerSync::from_config(config, filling_config).unwrap();
        
        let mut test_data = Vec::new();
        for i in 1..=5 {
            let mut row = HashMap::new();
            row.insert("emp_no".to_string(), Value::Number((100000 + i).into()));
            row.insert("first_name".to_string(), Value::String(format!("First{}", i)));
            row.insert("last_name".to_string(), Value::String(format!("Last{}", i)));
            test_data.push(row);
        }
        
        let result = filler.batch_insert("employees", test_data);
        // 在没有数据库连接的情况下，这个测试可能会失败，这是预期的行为
        match &result {
            Ok(count) => {
                assert_eq!(*count, 5);
            },
            Err(e) => {
                // 如果没有数据库连接，错误是预期的
                println!("数据库连接失败（在预期中）: {}", e);
                // 我们仍然可以检查错误类型是否正确
                // 但由于这是一个集成测试，我们接受任何数据库错误
            }
        }
    }

    /// 生成示例员工数据
    fn generate_sample_employee(index: usize) -> Value {
        let connection_config = ConnectionConfig::mysql("localhost", "demo", "root", "Aa123456")
            .with_port(13307)
            .with_param("charset", "utf8mb4");

        let filling_config = FillingConfig {
            batch_size: 100,
            use_transaction: true,
            timeout_seconds: 60,
            retry_count: 2,
        };

        let mut filler = MySqlFillerSync::from_config(connection_config, filling_config).unwrap();

        // 尝试从数据库获取实际的员工表结构
        match filler.get_table_schema("employees") {
            Ok(schema) => {
                // 使用实际的表结构生成数据
                crate::filling::utils::generate_sample_data_by_schema(&schema, index)
            },
            Err(_) => {
                // 如果无法获取表结构，创建一个最小化的通用表结构
                // 这样可以确保即使在没有数据库连接的情况下也能生成基本数据
                let generic_schema = TableSchema {
                    name: "employees".to_string(),
                    fields: vec![
                        FieldSchema {
                            name: "id".to_string(),
                            data_type: DataType::Integer { min: None, max: None },
                            constraints: crate::db::schema::FieldConstraints {
                                nullable: false,
                                unique: true,
                                default: None,
                                pattern: None,
                                min: None,
                                max: None,
                            },
                            description: None,
                            generator_config: None,
                            generator_type: None,
                        },
                    ],
                    primary_key: Some(vec!["id".to_string()]),
                    indexes: vec![],
                    description: None,
                };

                crate::filling::utils::generate_sample_data_by_schema(&generic_schema, index)
            }
        }
    }

}